#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import socket
import json
import os
from subprocess import PIPE, Popen


class ZCliper(object):
    def __init__(self, sock_path):
        self._cli = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        try:
            self._cli.connect(sock_path)
        except ConnectionRefusedError as e:
            print('socket %s 连接失败，zclipered 未启动' % sock_path)
            sys.exit(e.args[0])
        except Exception as e:
            print('socket %s 连接失败：%s' % (sock_path, e.args[1]))
            sys.exit(e.args[0])

    def __del__(self):
        if self._cli:
            self._cli.close()

    def send(self, cmd):
        try:
            self._cli.send(cmd.encode('utf-8'))
        except Exception as e:
            print('执行指令 %s 失败。错误原因：%s' % (cmd, e.args[1]))
            sys.exit(e.args[0])

    def recv(self):
        head = self._cli.recv(10)
        data = []
        idx = 0
        data_size = 0
        for i in head:
            if i == 123:
                break
            idx += 1
        data_size = int(head[:idx]) + idx

        data.append(head[idx:].decode('utf8'))
        tail_size = data_size - len(head)
        while tail_size > 0:
            b = self._cli.recv(tail_size)
            tail_size -= len(b)
            data.append(b.decode('utf8'))
        try:
            return json.loads(''.join(data))
        except:
            return {}

    def list(self):
        self.send('list')
        data = self.recv()
        ld = data.get('data')
        if ld is None:
            print('无法解析粘贴板数据')
            sys.exit(0)
        if not ld:
            print('粘贴板中无数据')
            sys.exit(0)

        return ld


def main():
    cliper = ZCliper(sys.argv[1])
    data = cliper.list()[::-1]
    # 按行解析 data
    filter_data = []
    for i in range(len(data)):
        k = ['%d. ' % i]
        item = data[i]
        k.append(item.strip().replace('\r\n', ' ').replace('\n', ' ')[:1024])
        filter_data.append(''.join(k))

    # 执行fzf
    filter_str = '\n'.join(filter_data)

    fzf = Popen(['fzf', '+s'], stdin=PIPE, stdout=PIPE)
    try:
        select, _ = fzf.communicate(filter_str.encode())
        select = select.decode('utf8')
        select_idx = int(select[:select.index('.')])
    except:
        # 没有选择终止了
        sys.exit(0)
    ret = os.system('printf "%s" | pbcopy' % data[select_idx])
    if ret == 0:
        print('已经复制到粘贴板')
    else:
        print('复制到粘贴板失败')


if __name__ == '__main__':
    main()
